<template>
  <div class="avatar-test">
    <h2>头像上传测试</h2>
    
    <div class="test-section">
      <h3>1. 选择文件测试</h3>
      <input type="file" @change="handleFileSelect" accept="image/*" />
      <div v-if="selectedFile">
        <p>选中文件: {{ selectedFile.name }}</p>
        <p>文件大小: {{ (selectedFile.size / 1024 / 1024).toFixed(2) }}MB</p>
        <p>文件类型: {{ selectedFile.type }}</p>
      </div>
    </div>
    
    <div class="test-section" v-if="previewUrl">
      <h3>2. 预览图片</h3>
      <img :src="previewUrl" alt="预览" style="max-width: 200px; max-height: 200px;" />
    </div>
    
    <div class="test-section">
      <h3>3. 上传测试</h3>
      <el-button type="primary" @click="testUpload" :loading="uploading" :disabled="!selectedFile">
        测试上传
      </el-button>
    </div>
    
    <div class="test-section" v-if="uploadResult">
      <h3>4. 上传结果</h3>
      <pre>{{ JSON.stringify(uploadResult, null, 2) }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElButton } from 'element-plus'
import avatarApi from '@/api/avatar'

const selectedFile = ref(null)
const previewUrl = ref('')
const uploading = ref(false)
const uploadResult = ref(null)

const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    selectedFile.value = file
    
    // 创建预览
    const reader = new FileReader()
    reader.onload = (e) => {
      previewUrl.value = e.target.result
    }
    reader.readAsDataURL(file)
    
    console.log('选中文件:', file)
  }
}

const testUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.error('请先选择文件')
    return
  }
  
  try {
    uploading.value = true
    uploadResult.value = null
    
    console.log('开始上传文件:', selectedFile.value)
    
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    
    console.log('FormData创建完成:', formData)
    
    const response = await avatarApi.uploadAvatar(formData)
    
    console.log('上传响应:', response)
    uploadResult.value = response
    
    if (response.code === 200) {
      ElMessage.success('上传成功!')
    } else {
      ElMessage.error(response.message || '上传失败')
    }
    
  } catch (error) {
    console.error('上传错误:', error)
    uploadResult.value = { error: error.message, response: error.response?.data }
    ElMessage.error('上传失败: ' + error.message)
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.avatar-test {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.test-section {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.test-section h3 {
  margin-top: 0;
  color: #333;
}

pre {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}
</style> 